<template>
    <div class="purchase-container">
        <el-form
            ref="purchaseFormRef"
            class="w-full grid grid-cols-2 gap-3"
            label-position="top"
            label-width="auto"
            :model="purchaseForm"
            :rules="rules"
        >
            <el-form-item label="客户：" required prop="customerAbbreviation">
                <el-autocomplete
                    v-model="purchaseForm.customerAbbreviation"
                    placeholder="请选择客户"
                    clearable
                    :fetch-suggestions="queryCustomerSearch"
                    @select="handleCustomerSelect"
                />
            </el-form-item>
            <el-form-item label="供应商：" required prop="supplierAbbreviation">
                <el-autocomplete
                    v-model="purchaseForm.supplierAbbreviation"
                    placeholder="请选择供应商"
                    clearable
                    :fetch-suggestions="querySupplierSearch"
                    @select="handleSupplierSelect"
                />
            </el-form-item>

            <el-form-item label="产品名称：" required prop="productName">
                <el-autocomplete
                    v-model="purchaseForm.productName"
                    placeholder="选择客户后，再选择产品名称"
                    :fetch-suggestions="queryProductSearch"
                    clearable
                    @select="handleProductSelect"
                />
            </el-form-item>
            <el-form-item label="产品尺寸：" required>
                <el-input v-model="purchaseForm.productSize" disabled></el-input>
            </el-form-item>

            <el-form-item label="面纸尺寸（二选一）：">
                <el-input v-model="purchaseForm.tissueSize"></el-input>
            </el-form-item>
            <el-form-item label="瓦楞尺寸（二选一）：">
                <el-input v-model="purchaseForm.corrugatedSize"></el-input>
            </el-form-item>

            <el-form-item label="材质：" required>
                <el-input v-model="purchaseForm.materialQuality"></el-input>
            </el-form-item>
            <el-form-item label="压线：">
                <el-input v-model="purchaseForm.crimping"></el-input>
            </el-form-item>

            <!-- 拼数 / 采购等级 / 备货量 / 采购数量 / 送货地址 -->
            <div class="flex justify-between col-span-2">
                <el-form-item label="拼数：" required>
                    <el-input v-model="purchaseForm.spell" disabled></el-input>
                </el-form-item>
                <el-form-item label="订单状态：" required>
                    <el-select v-model="purchaseForm.orderStatus" placeholder="请选择订单状态" style="width: 200px">
                        <el-option v-for="(item, index) in orderStatusOptions" :key="index" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="采购量：" required prop="purchaseNumber">
                    <el-input-number v-model="purchaseForm.purchaseNumber" :min="0" :step="5" />
                </el-form-item>
                <el-form-item label="送货地址：" required prop="arrivalTo">
                    <el-autocomplete v-model="purchaseForm.arrivalTo" placeholder="请选择送货地址" :fetch-suggestions="queryArrivalToSearch" />
                </el-form-item>
            </div>

            <el-form-item class="col-span-2" label="订单备注：">
                <el-input type="textarea" v-model="purchaseForm.orderRemark" autosize></el-input>
            </el-form-item>
            <el-form-item class="col-span-2" label="采购备注：">
                <el-input type="textarea" v-model="purchaseForm.purchaseNotes" autosize></el-input>
            </el-form-item>

            <el-form-item class="col-span-2">
                <div class="w-full flex justify-end">
                    <el-button type="primary" @click="handleSubmit(purchaseFormRef)">提交</el-button>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { getCustomerList } from '@/api/customer';
import { getProductList } from '@/api/product';
import { productPurchase } from '@/api/purchase';
import { getSupplierList } from '@/api/supplier';
import router from '@/router';
import { usePurchaseStore } from '@/store/modules/purchase';
import { useSystemStore } from '@/store/modules/system';
import { useUserStore } from '@/store/modules/user';
import { FormInstance, FormRules } from 'element-plus';

onMounted(async () => {
    // 检查是否有风险
    if (usePurchaseStore().riskAssessment.length >= 10) {
        ElMessage({
            type: 'error',
            message: "当前系统已开启风险检查，订单提交前请先处理风险隐患",
            showClose: true,
            duration: 0,
        });
        // 权限检查
        if (!useUserStore().checkPermission('purchase:list')) {
            ElMessage.error('您没有处理采购风险的权限，请联系管理员');
            // 跳转回主页
            router.push({ name: 'Index' });
            return;
        }
        // 跳转至供应商采购页面处理风险隐患
        router.push({ name: 'SupplierPurchase' });
    }
    // 获取客户列表
    await updateCustomerList();
    // 获取供应商列表
    await updateSupplierList();
});

// system的store
const system = useSystemStore();
// 计算宽度
const purchaseContainerWidth = computed(() => {
    return system.config.isCollapse ? 'calc(100vw - 84px)' : 'calc(100vw - 220px)';
});

/* ******************************客户列表属性/方法****************************** */
// 客户列表
const customerList = reactive<AjaxResponse['customerList']>([]);
// 查询所有激活的客户
const updateCustomerList = async () => {
    getCustomerList(true).then((res) => {
        res.data.forEach((item) => {
            item.value = item.customerAbbreviation;
            customerList.push(item);
        });
    });
};
// 匹配客户列表 -- 通过客户id
const matchCustomerInfo = (id: string): { customerName: string; customerAbbreviation: string } => {
    const obj: { customerName: string; customerAbbreviation: string } = {
        customerName: '未知',
        customerAbbreviation: '未知',
    };
    for (let index = 0; index < customerList.length; index++) {
        const customer = customerList[index];
        if (customer._id == id) {
            obj.customerName = customer.customerName;
            obj.customerAbbreviation = customer.customerAbbreviation;
            break;
        }
    }
    return obj;
};

const queryCustomerSearch = (queryString: string, cb: any) => {
    // 过滤器
    const createFilter = (queryString: string) => {
        return (customer: (typeof customerList)[0]) => {
            return new RegExp(queryString).test(customer.customerName);
        };
    };

    const results = queryString ? customerList.filter(createFilter(queryString)) : customerList;
    // call callback function to return suggestions
    cb(results);
};
// 选择客户时的回调
const handleCustomerSelect = (item: any) => {
    // 加载客户的产品库
    getProductList(item._id).then((res) => {
        if (res.data.length == 0) {
            ElMessage({
                message: '该客户下没有产品，请先添加产品',
                type: 'error',
                duration: 2500,
            });
            return;
        }
        res.data.forEach((item) => {
            item.value = item.productName;
            productList.push(item);
        });
    });
    // 匹配客户信息
    const obj = matchCustomerInfo(item._id);
    purchaseForm.customerId = item._id;
    purchaseForm.customerAbbreviation = obj.customerAbbreviation;
};

/* ******************************供应商属性/方法****************************** */
// 供应商列表
const supplierList = reactive<AjaxResponse['supplierList']>([]);
// 查询所有激活的供应商
const updateSupplierList = async () => {
    getSupplierList(true).then((res) => {
        res.data.forEach((item) => {
            item.value = item.supplierAbbreviation;
            supplierList.push(item);
        });
    });
};
// 供应商列表搜索
const querySupplierSearch = (queryString: string, cb: any) => {
    // 过滤器
    const createFilter = (queryString: string) => {
        return (supplier: (typeof supplierList)[0]) => {
            return new RegExp(queryString).test(supplier.supplierName);
        };
    };

    const results = queryString ? supplierList.filter(createFilter(queryString)) : supplierList;
    // call callback function to return suggestions
    cb(results);
};
// 选择供应商时的回调
const handleSupplierSelect = (item: any) => {
    purchaseForm.supplierId = item._id;
    purchaseForm.supplierAbbreviation = item.supplierAbbreviation;
};

/* ******************************产品列表属性/方法****************************** */
// 产品列表
const productList = reactive<AjaxResponse['productList']>([]);
// 产品列表搜索
const queryProductSearch = (queryString: string, cb: any) => {
    if (purchaseForm.customerAbbreviation === '') {
        ElMessage({
            message: '请先选择客户',
            type: 'error',
            duration: 2500,
        });
        return;
    }

    // 过滤器
    const createFilter = (queryString: string) => {
        return (product: AjaxResponse['productList'][0]) => {
            // 正则处理特殊符号
            const regex = /[.*+?^${}()|[\]\\]/;
            const match = queryString.replace(regex, '\\$&');
            const reg = new RegExp(match, 'i');
            if (reg.test(product.productName)) {
                return true;
            }
        };
    };
    const results = queryString ? productList.filter(createFilter(queryString)) : productList;
    // call callback function to return suggestions
    cb(results);
};
// 选择产品时的回调
const handleProductSelect = (item: any) => {
    purchaseForm.productName = item.productName;
    purchaseForm.productId = item._id;
    purchaseForm.productSize = item.productSize;
    purchaseForm.tissueSize = item.tissueSize;
    purchaseForm.corrugatedSize = item.corrugatedSize;
    purchaseForm.materialQuality = item.materialQuality;
    purchaseForm.crimping = item.crimping;
    purchaseForm.spell = item.spell;
    // 提示工艺
    ElMessage({
        message: `🚀工艺：${item.process !== '' && item.process !== undefined ? item.process : '未登记'}。
        🚀描述：${item.description !== '' && item.description !== undefined ? item.description : '未登记'}`,
        type: 'info',
        duration: 0,
        showClose: true,
    });
};

/* ******************************表单属性/方法****************************** */
// 表单ref
const purchaseFormRef = ref();
// 采购表单
const purchaseForm = reactive<AjaxRequest['purchaseForm']>({
    customerId: '',
    customerAbbreviation: '',
    supplierId: '',
    supplierAbbreviation: '',
    orderStatus: 'primary',
    orderNo: '尚未分配',
    productName: '',
    productId: '',
    productSize: '',
    tissueSize: '',
    corrugatedSize: '',
    materialQuality: '',
    crimping: '',
    spell: 0,
    // 这条字段没用，只是为了兼容
    orderNumber: 0,
    purchaseNumber: 0,
    stockNumber: 0,
    arrivalTo: '',
    orderRemark: '',
    purchaseNotes: '',
    orderDeliveryDate: '',
    creator: '',
    creatorId: '',
});
// 采购等级
const orderStatusOptions = [
    { label: '正常', value: 'primary' },
    { label: '加急', value: 'warning' },
    { label: '特急', value: 'danger' },
];
// 采购表单校验规则
const rules = reactive<FormRules<typeof purchaseForm>>({
    customerAbbreviation: [{ required: true, message: '请选择客户' }],
    supplierAbbreviation: [{ required: true, message: '请选择供应商' }],
    productName: [{ required: true, message: '请选择产品名称' }],
    purchaseNumber: [{ required: true, message: '请输入采购数量' }],
    stockNumber: [{ required: true, message: '请输入备货数量' }],
    arrivalTo: [{ required: true, message: '请选择到货地址' }],
});
// 到货地址搜索
const queryArrivalToSearch = (queryString: string, cb: any) => {
    // 过滤器
    const createFilter = (queryString: string) => {
        return (arrival: (typeof arrivalToArray)[0]) => {
            return new RegExp(queryString).test(arrival.value);
        };
    };

    if (system.purchase.deliveryAddress.length == 0) {
        ElMessage.warning('系统采购配置信息为空，请先配置！方便后续下单！');
    }

    // 创建数据
    const arrivalToArray: any[] = [];
    // 从系统配置中，添加数据
    system.purchase.deliveryAddress.forEach((item) => {
        arrivalToArray.push({
            label: item,
            value: item,
        });
    });
    const results = queryString ? arrivalToArray.filter(createFilter(queryString)) : arrivalToArray;
    // call callback function to return suggestions
    cb(results);
};
// 提交产品采购
const handleSubmit = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    purchaseFormRef.value.validate(async (valid: boolean) => {
        if (valid) {
            // 提交
            productPurchase(purchaseForm).then(() => {
                ElMessage({
                    message: '提交成功',
                    type: 'success',
                    duration: 2500,
                });
                purchaseForm.productName = '';
                purchaseForm.productSize = '';
                purchaseForm.tissueSize = '';
                purchaseForm.corrugatedSize = '';
                purchaseForm.materialQuality = '';
                purchaseForm.crimping = '';
                purchaseForm.spell = 0;
                purchaseForm.purchaseNumber = 0;
            });
        } else {
            ElMessage({
                message: '请填写完整信息',
                type: 'error',
                duration: 2500,
            });
            return false;
        }
    });
};
</script>

<style lang="scss" scoped>
.purchase-container {
    width: v-bind(purchaseContainerWidth);
    height: calc(100vh - 80px);
    display: flex;
    align-items: center;
}
</style>
